console.log('启动演练', $event);
const $list = this.pageObj.getApiWidgetByAliasName('list')?.widgetObj;
// 变量
let params = this.pageObj.getVariables().find(v => v.name === "screen_params")?.value;
const prefix = this.pageObj.getVariables().find(v => v.name === "environmentType")?.value;
const search = this.pageObj.getApiWidgetByAliasName('search')?.widgetObj

try {
  // 路由参数
  params = params ? JSON.parse(params) : {
    id: '1765642885643964417',
    eventType: '1742818710932074497',
    eventLevel: '1692442354007216130',
  };
} catch (error) {
  params = {}
  console.error(error)
}

function baseFetch(url, params) {
  return fetch(url, {
    method: 'POST',
    headers: { "Content-type": "application/json" },
    body: JSON.stringify(params),
  }).then(res => res.json())
}

const startDrill = (drillPersonInfoDictTreeNodes, resData) => {
  if (!params?.id) return;

  const options = {
    ...params,
    emergencyPlan: JSON.stringify({
      emergencyResource: resData,
      eventId: params.eventId || params.id,
      planId: search.getFormData('form_1')?.name,
      eventLocation: params.drillLocation,
      eventNature: params.eventQualityCode,
      eventRegion: params.occurrencePlace,
      eventLevel: params.eventLevel,
      eventType: params.eventType,
    }),
    // 演练组织典信息
    drillPersonInfoDictTreeNodes,
    eventId: params.eventId || params.id,
    eventType: params.eventType,
    eventLevel: params.eventLevel,
    pointId: '',
    disableFlag: 2,
  };

  console.log('save: options => ', options);
  baseFetch(`/${prefix}Event/drillPlanInfo/update`, options).then(({ success }) => {
    if (success) {
      console.log('save');
      window.layer?.msg('启动成功');
      this.getApiPage().navigateStage('843057919439142912', [{ name: 'screen_params', value: JSON.stringify(options) }])
    }
  });
}

function hasRooter ({ drillRoleCode, drillRole } = {}) {
  return drillRoleCode === '1720262536462589954' || drillRole === '总指挥'
}

function hasGrouper ({ drillRoleCode, drillRole } = {}) {
  return drillRoleCode === '7cd6254d-6e66-45a6-ab61-de17eebff425'
      || drillRole === '组长'
}

function findPerson(personTree) {
  return personTree.drillPersonInfos.find(v => v);
}

function findRooter(personTree) {
  return personTree.drillPersonInfos.find(hasRooter)
}

function findGrouper(personTree) {
  return personTree.drillPersonInfos.find(hasGrouper)
}

function findDrillRoot(personTree, findRole) {
  let role;
  if (Array.isArray(personTree)) {
    role = personTree.find(person => findDrillRoot(person, findRole))
    if (role) return role;
  }

  if (personTree?.drillPersonInfos?.length) {
    role = findRole(personTree);
    if (role) return role;
  }

  if (personTree?.drillPersonInfoDictTreeNodes?.length) {
    role = findDrillRoot(personTree.drillPersonInfoDictTreeNodes, findRole)
    if (role) return role;
  }
}

if ($list) {
// 演练数据
  const { emergencyGroup, ...resData } = $list?.getStartUpParams();
  const personTree = $list.getGroupData()

  console.log('verify', { emergencyGroup, ...resData });
  if (personTree?.length) {
    const persons = findDrillRoot(personTree, findPerson)
    if (persons) {
      const rooter = findDrillRoot(personTree, findRooter)
      if (rooter) {
        let group;
        const noGrouper = findDrillRoot(personTree, (tree) => {
          if (tree.dictCode !== 'emergency_drill_headquarters') { // 排除指挥部
            if (!findGrouper(tree)) {
              // 如果这个组不存在
              return group = tree;
            }
          }
        })
        if (noGrouper) {
          window.layer?.msg(`"${group.dictName}"未选择组长，请选择组长！`)
        } else {
          startDrill (personTree, resData)
        }
      } else {
        window.layer?.msg('请选择总指挥！')
      }
    } else {
      window.layer?.msg('请选择演练人员！')
    }
  } else {
    window.layer?.msg('请添加演练组织！')
  }
}
